﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Globalization;

namespace Sherwood.Tests
{
    [TestClass]
    public class OtherTests
    {
        [TestMethod]
        public void TestMethod1()
        {
            bool result = LooseMatch("Hückel", "Huckel");
        }


        /// <summary>
        /// Matches two strings loosly by ignoring case and removing all special characters.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        private static bool LooseMatch(string a, string b)
        {

            const string allowedCharacters = "abcdefghijklmnopqrstuvwxyzæøå@";
            if (!string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b))
            {
                a = RemoveDiacritics(a).ToLower().Trim();
                b = RemoveDiacritics(b).ToLower().Trim();
                a = a.Where(t => allowedCharacters.Contains(t)).Aggregate("", (current, t) => current + t);
                b = b.Where(t => allowedCharacters.Contains(t)).Aggregate("", (current, t) => current + t);
                return a.Equals(b);
            }
            return false;
        }

        //Source: http://blogs.msdn.com/b/michkap/archive/2007/05/14/2629747.aspx
        private static string RemoveDiacritics(string stIn)
        {
            string stFormD = stIn.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }

            return (sb.ToString().Normalize(NormalizationForm.FormC));
        }
    }
}
